﻿using System;
using System.IO;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;

using Gola.VN.Scb.Web.Common.Models;
using System;
using Gola.VN.Scb.Web.Common.Entities;
using Gola.VN.Scb.Web.Presentation.Helpers;
using Gola.VN.Scb.Web.Presentation.Models;

namespace Gola.VN.Scb.Web.Presentation.Controllers
{
    [HandleError]
    public class CustomerController : Controller
    {
        #region properties

        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }

        #endregion

        #region initliaze

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null)
            {
                FormsService = new FormsAuthenticationService();
            }
            if (MembershipService == null)
            {
                MembershipService = new AccountMembershipService();
            }

            base.Initialize(requestContext);
        }

        #endregion

        #region register

        public ActionResult Register()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Register(CustomerModel customer)
        {
            if (ModelState.IsValid)
            {
                // 0. validate image size
                if (!IsValidSize())
                {
                    ModelState.AddModelError("Image", "Ảnh của bạn có dung lương > 50KB");
                    return View(customer);
                }

                // 1. register user to membership database
                MembershipCreateStatus createStatus = MembershipService.CreateUser(customer.UserName, customer.Password,
                                                                                   customer.Email);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    FormsService.SignIn(customer.UserName, false);

                    // 2. register to scb database
                    var provider = new ProviderEntity();
                    provider.Name = customer.UserName;
                    provider.DisplayName = customer.FullName;
                    provider.Address = customer.Address;
                    provider.Email = customer.Email;
                    provider.PhoneNumber = customer.PhoneNumber;
                    provider.Logo = SaveImage(customer.UserName, true, "Image", customer.Image);

                    MainService.GetInstant().ProviderService.Insert(provider);

                    return RedirectToAction("Index", "Home");
                }
                else
                    ModelState.AddModelError("UserName", AccountValidation.ErrorCodeToString(createStatus));
            }

            return View(customer);
        }

        #endregion

        #region logon

        public ActionResult LogOn()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ValidateUser(model.UserName, model.Password))
                {
                    FormsService.SignIn(model.UserName, model.IsRemember);
                    if (!string.IsNullOrEmpty(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                    ModelState.AddModelError("IsRemember", "Tên đăng nhập hoặc mật khẩu không đúng.");
            }

            return View(model);
        }

        #endregion

        #region logOff

        public ActionResult LogOff()
        {
            FormsService.SignOut();

            return RedirectToAction("Index", "Home");
        }

        #endregion

        #region password

        [Authorize]
        public ActionResult ChangePassword()
        {
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.Password))
                {
                    return RedirectToAction("NotifyMessage", BuildNotifyParameters("Thay đổi mật khẩu",
                                                                                   "Bạn đã thay đổi mật khẩu thành công."));
                }
                else
                {
                    ModelState.AddModelError("RePassword", "Mật khẩu cũ không đúng hoặc mật khẩu mới không hợp lệ.");
                }
            }

            return View(model);
        }

        #endregion

        #region change informations

        [Authorize]
        public ActionResult CustomerChangeInformation()
        {
            var customerInfo = new CustomerChangeInfoModel();

            ProviderEntity provider = MainService.GetInstant().ProviderService.GetProvider(Membership.GetUser().UserName);

            customerInfo.UserName = provider.Name;
            customerInfo.Id = provider.Id;
            customerInfo.FullName = provider.DisplayName;
            customerInfo.Address = provider.Address;
            customerInfo.Email = provider.Email;
            customerInfo.PhoneNumber = provider.PhoneNumber;
            customerInfo.Image = provider.Logo;

            return View(customerInfo);
        }

        [Authorize]
        [HttpPost]
        public ActionResult CustomerChangeInformation(CustomerChangeInfoModel customerInfo)
        {
            if (ModelState.IsValid)
            {
                if (!IsValidSize())
                {
                    ModelState.AddModelError("Image", "Ảnh của bạn có dung lương > 50KB");
                    return View(customerInfo);
                }

                // 2. register to scb database
                try
                {
                    var provider = new ProviderEntity();
                    provider.Id = customerInfo.Id;
                    provider.Name = customerInfo.UserName;
                    provider.DisplayName = customerInfo.FullName;
                    provider.Address = customerInfo.Address;
                    provider.Email = customerInfo.Email;
                    provider.PhoneNumber = customerInfo.PhoneNumber;
                    provider.Logo = SaveImage(customerInfo.UserName, true, "Image", customerInfo.Image);

                    MainService.GetInstant().ProviderService.Update(provider);

                    return RedirectToAction("NotifyMessage", BuildNotifyParameters("Thay đổi thông tin",
                                                                                   "Bạn đã thay đổi thông tin gian hàng thành công."));
                }
                catch
                {
                    ModelState.AddModelError("UserName",
                                             "Cập nhật thông tin không thành công. Bạn vui lòng thử lại sau.");
                    return View(customerInfo);
                }
            }

            return View(customerInfo);
        }

        #endregion

        #region notify message

        public ActionResult NotifyMessage(string title, string message)
        {
            if (string.IsNullOrEmpty(title) || string.IsNullOrEmpty(message))
                RedirectToAction("Index", "Home");

            ViewData["Title"] = title;
            ViewData["Message"] = message;

            return View();
        }

        #endregion

        #region store

        public ActionResult CustomerStore(string userName, string categoryName = "")
        {
            if (!string.IsNullOrEmpty(userName) && Membership.GetUser(userName) != null)
                return View("CustomerStore", GetCustomInfor(userName, categoryName));
            else
            {
                var cusModel = new UICustomerModels();
                cusModel.Providers = MainService.GetInstant().ProviderService.GetCustomers();

                return View("AllStore", cusModel);
            }
        }

        private UICustomerModels GetCustomInfor(string userName, string categoryName)
        {
            var cusModel = new UICustomerModels();

            ProviderEntity provider = MainService.GetInstant().ProviderService.GetProvider(userName);
            if (provider != null)
            {
                // customer information
                cusModel.Customer.UserName = userName;
                cusModel.Customer.FullName = provider.DisplayName;
                cusModel.Customer.Address = provider.Address;
                cusModel.Customer.Image = provider.Logo;

                // categories information
                //provider.Id = 1;// ngocbv: cheat
                // cusModel.Categories = CategoryService.GetByProviderId(provider.Id); //todo: replaced by ngocbv
                cusModel.Categories = MainService.GetInstant().CategoryService.GetCategoriesByProviderId(provider.Id);

                // products information
                // cusModel.Products = ProductService.GetProductsByProviderIdAndCategoryName(categoryName, provider.Id); //todo: ngocbv
                cusModel.Products = MainService.GetInstant().ProductService.GetProductsByProviderIdAndCategoryName(categoryName, provider.Id);
                cusModel.Products = Utilities.GetPageView(1, cusModel.Products); // todo: implement paging
            }

            cusModel.IsAuthenticated = User.Identity.IsAuthenticated;

            return cusModel;
        }

        #endregion

        #region add product

        [Authorize]
        public ActionResult AddProduct()
        {
            var proModel = new ProductModel();
            // proModel.Categories = CategoryService.GetCategoriesAsTree; //todo: replaced by ngocbv
            proModel.Categories = MainService.GetInstant().CategoryService.GetCategoriesAsTree();

            return View(proModel);
        }

        [Authorize]
        [HttpPost]
        public ActionResult AddProduct(ProductModel product)
        {
            #region 1. process dropdownlist for category

            // product.Categories = CategoryService.GetCategoriesAsTree; //todo: replaced by ngocbv
            product.Categories = MainService.GetInstant().CategoryService.GetCategoriesAsTree();

            // select category
            if (product.CategoryLevel == "1")
            {
                product.SubCategories =
                    product.Categories.Find(c => c.Id.ToString() == product.CategoryId).SubCategories;

                product.CategoryLevel = "0";
                return View(product);
            }

            // select subcategory
            if (product.CategoryLevel == "2")
            {
                product.SubCategories =
                    product.Categories.Find(c => c.Id.ToString() == product.CategoryId).SubCategories;
                product.SubSubCategories = product.SubCategories.Find(c => c.Id.ToString() ==
                                                                           product.SubCategoryId).SubCategories;

                product.CategoryLevel = "0";
                return View(product);
            }

            #endregion

            #region 2. validate

            // 1. category
            if (string.IsNullOrEmpty(product.SubSubCategoryId))
                ModelState.AddModelError("SubSubCategoryId", "Bạn phải chọn danh mục cho sản phẩm");
            else if (product.SubSubCategoryId == "-1")
                product.SubSubCategoryId = product.SubCategoryId;
            // 2. title
            if (string.IsNullOrEmpty(product.Title))
                ModelState.AddModelError("Title", "Bạn phải nhập tên sản phẩm");
            // 3. description
            if (string.IsNullOrEmpty(product.Description))
                ModelState.AddModelError("Description", "Bạn phải nhập mô tả cho sản phẩm");
            // 4. image
            if (!IsValidSize())
                ModelState.AddModelError("ImageUrl", "Bạn phải nhập mô tả cho sản phẩm");
            else
                product.ImageUrl = SaveImage(Membership.GetUser().UserName, false, "ImageUrl", product.ImageUrl);
            // 5. price
            if (product.OldPrice < 0)
                ModelState.AddModelError("OldPrice", "Giá phải > 0");
            // 6. old price
            if (product.Price < 0)
                ModelState.AddModelError("Price", "Giá bán phải > 0");

            #endregion

            #region 3. insert into database

            if (ModelState.IsValid)
            {
                var dtoProduct = new ProductEntity();
                dtoProduct.CategoryId = int.Parse(product.SubSubCategoryId);
                dtoProduct.Description = product.Description;
                dtoProduct.ImageUrl = product.ImageUrl;
                dtoProduct.LastPrice = product.OldPrice;
                dtoProduct.Price = product.Price;
                dtoProduct.Promotion = string.IsNullOrEmpty(product.Promotion) ? "" : product.Promotion;
                dtoProduct.Title = product.Title;
                dtoProduct.ProviderId = MainService.GetInstant().ProviderService.GetProvider(Membership.GetUser().UserName).Id;
                dtoProduct.Currency = "VND";

                // bool isSuccess = ProductService.Insert(dtoProduct); //todo: ngocbv
                bool isSuccess = MainService.GetInstant().ProductService.InsertProduct(dtoProduct);
                RouteValueDictionary parameters = BuildNotifyParameters("Thêm mới sản phẩm",
                                                                        isSuccess
                                                                            ? "Sản phẩm của bạn đã được thêm thành công."
                                                                            : "Có lỗi xảy ra trong quá trình thêm sản phẩm. Bạn vui lòng thử lại sau.");

                return RedirectToAction("NotifyMessage", parameters);
            }

            #endregion

            return View(product);
        }

        #endregion

        #region helper methods

        /// <summary>
        /// 
        /// </summary>
        /// <param name="title"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        private RouteValueDictionary BuildNotifyParameters(string title, string message)
        {
            var parameters = new RouteValueDictionary();
            parameters.Add("Title", title);
            parameters.Add("Message", message);

            return parameters;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private string SaveImage(string userName, bool isProvider = true,
                                 string propertyName = "Image", string defaultImage = "../../Content/logos/default.gif")
        {
            if (Request.Files != null && Request.Files.Count > 0)
            {
                HttpPostedFileBase httpPostedFile = Request.Files[0];
                string fileName = userName + (isProvider
                                                  ? Path.GetFileName(httpPostedFile.FileName)
                                                  : Guid.NewGuid() + Path.GetExtension(httpPostedFile.FileName));
                string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + @"Content\Logos\",
                                               fileName);
                httpPostedFile.SaveAs(filePath);

                return "../../Content/logos/" + fileName;
            }

            return string.IsNullOrEmpty(defaultImage) ? "../../Content/logos/default.gif" : defaultImage;
        }

        private bool IsValidSize()
        {
            if (Request.Files != null && Request.Files.Count > 0)
            {
                HttpPostedFileBase httpPostedFile = Request.Files[0];
                Stream stream = httpPostedFile.InputStream;

                if (stream.Length > 50 * 1024)
                    return false;
            }

            return true;
        }

        #endregion
    }

    #region helper classes

    public interface IMembershipService
    {
        int MinPasswordLength { get; }

        bool ValidateUser(string userName, string password);
        MembershipCreateStatus CreateUser(string userName, string password, string email);
        bool ChangePassword(string userName, string oldPassword, string newPassword);
    }

    public class AccountMembershipService : IMembershipService
    {
        private readonly MembershipProvider _provider;

        public AccountMembershipService()
            : this(null)
        {
        }

        public AccountMembershipService(MembershipProvider provider)
        {
            _provider = provider ?? Membership.Provider;
        }

        #region IMembershipService Members

        public int MinPasswordLength
        {
            get { return _provider.MinRequiredPasswordLength; }
        }

        public bool ValidateUser(string userName, string password)
        {
            if (String.IsNullOrEmpty(userName))
                throw new ArgumentException("Value cannot be null or empty.", "userName");
            if (String.IsNullOrEmpty(password))
                throw new ArgumentException("Value cannot be null or empty.", "password");

            return _provider.ValidateUser(userName, password);
        }

        public MembershipCreateStatus CreateUser(string userName, string password, string email)
        {
            if (String.IsNullOrEmpty(userName))
                throw new ArgumentException("Value cannot be null or empty.", "userName");
            if (String.IsNullOrEmpty(password))
                throw new ArgumentException("Value cannot be null or empty.", "password");
            if (String.IsNullOrEmpty(email)) throw new ArgumentException("Value cannot be null or empty.", "email");

            MembershipCreateStatus status;
            _provider.CreateUser(userName, password, email, null, null, true, null, out status);
            return status;
        }

        public bool ChangePassword(string userName, string oldPassword, string newPassword)
        {
            if (String.IsNullOrEmpty(userName))
                throw new ArgumentException("Value cannot be null or empty.", "userName");
            if (String.IsNullOrEmpty(oldPassword))
                throw new ArgumentException("Value cannot be null or empty.", "oldPassword");
            if (String.IsNullOrEmpty(newPassword))
                throw new ArgumentException("Value cannot be null or empty.", "newPassword");

            // The underlying ChangePassword() will throw an exception rather
            // than return false in certain failure scenarios.
            try
            {
                MembershipUser currentUser = _provider.GetUser(userName, true /* userIsOnline */);
                return currentUser.ChangePassword(oldPassword, newPassword);
            }
            catch (ArgumentException)
            {
                return false;
            }
            catch (MembershipPasswordException)
            {
                return false;
            }
        }

        #endregion
    }

    public interface IFormsAuthenticationService
    {
        void SignIn(string userName, bool createPersistentCookie);
        void SignOut();
    }

    public class FormsAuthenticationService : IFormsAuthenticationService
    {
        #region IFormsAuthenticationService Members

        public void SignIn(string userName, bool createPersistentCookie)
        {
            if (String.IsNullOrEmpty(userName))
                throw new ArgumentException("Value cannot be null or empty.", "userName");

            FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
        }

        public void SignOut()
        {
            FormsAuthentication.SignOut();
        }

        #endregion
    }

    public static class AccountValidation
    {
        public static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "Username already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A username for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return
                        "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return
                        "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return
                        "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
    }

    #endregion
}